﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using FazaDemo.PL.AbstractPresenters;
using FazaDemo.PL.Wpf.Browser;
using FazaDemo.ViewModels;
using FazaDemo.BL.InterfaceDomain;


namespace FazaDemo.PL.Wpf
{
    public class WorkAreaPresenter
    {

        private const string WorkArea = "WorkArea";

        private readonly BasePresenter _presenter;

        private readonly IWorkAreaViewModel _viewModel;

        public WorkAreaPresenter(BasePresenter presenter, IWorkAreaViewModel viewModel)
        {
            _presenter = presenter;
            _viewModel = viewModel;
        }

        public Page Initialize()
        {
            return _presenter.Initialize(new PresenterType { Name = WorkArea });
        }

        public void BuildElements(Page area)
        {
            var workArea = area as WorkArea;
            if (workArea != null)
            {
                IEnumerable<Menu_Item> items = _viewModel.Items;
                BuildMenu(items, items, workArea.P_MainMenu, new List<Menu_Item>());
            }
        }

        private void BuildMenu(IEnumerable<Menu_Item> source, IEnumerable<Menu_Item> globalSource, 
            object parent, IList<Menu_Item> writedItems)
        {
            foreach (var item in source)
            {
                Menu mainMenu = null;
                MenuItem curItem = null;
                if (parent is Menu)
                {
                    mainMenu = parent as Menu;
                }
                if (parent is MenuItem)
                {
                    curItem = parent as MenuItem;
                }
                if (writedItems.Where(i => i.Id == item.Id).ToList().Count == 0)
                {
                    object menuItem = null;
                    if (parent is Menu)
                    {
                        mainMenu.Items.Add(new MenuItem{ Header = item.Text});
                        menuItem = mainMenu.Items[mainMenu.Items.Count - 1];
                    }
                    if (parent is MenuItem)
                    {
                        curItem.Items.Add(new MenuItem { Header = item.Text });
                        menuItem = curItem.Items[curItem.Items.Count - 1];
                    }
                    writedItems.Add(item);
                    var curChilds = globalSource.Where(s => s.ParentId == item.Id).ToList();
                    if (curChilds.Count > 0)
                    {
                        BuildMenu(curChilds, globalSource, menuItem, writedItems);
                    }
                }
            }
        }

    }
}
